/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package graphic;

import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.input.MouseEvent;

/**
 *
 * @author David
 */
public abstract class Movable extends DiagramComponent {
  
  public static final int SIZE = 100;
  public static final Cursor CURSOR_MOUSE_ENTER = Cursor.MOVE;
  
  private double startDragX;
  private double startDragY;
  private Point2D dragAnchor;
  private Cursor saveMouseCursor;
  
  
  public Movable() {
    super();
    initialize();
  }
  
  public Movable(Point2D location) {
    super(location);
    initialize();
  }
  
  private void initialize() {
    
    // turn on caching so the jigsaw piece is fasr to draw when dragging
    setCache(true);
    registerEvents();
  }
  
  private void registerEvents()
  {    
    setOnMouseEntered(new EventHandler<MouseEvent>() {

      @Override
      public void handle(MouseEvent arg0) {
        saveAndSetCursor(CURSOR_MOUSE_ENTER);
      }
    });
    
    setOnMouseExited(new EventHandler<MouseEvent>() {

      @Override
      public void handle(MouseEvent arg0) {
        restoreCursor();
      }
    });

    setOnMousePressed(new EventHandler<MouseEvent>() {
      
      @Override
      public void handle(MouseEvent me) {
        initDragging(me);
      }
    });
    
    setOnMouseDragged(new EventHandler<MouseEvent>() {

        @Override
      public void handle(MouseEvent me) {
          computeDraggingTranslate(me);
      }
    });
  }
  
  private void initDragging(MouseEvent me)
  {
    toFront();
    startDragX = getTranslateX();
    startDragY = getTranslateY();
    dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
  }
  
  private void computeDraggingTranslate(MouseEvent me)
  {
    double newTranslateX = startDragX + me.getSceneX() - dragAnchor.getX();
    double newTranslateY = startDragY + me.getSceneY() - dragAnchor.getY();

    setTranslateX(newTranslateX);
    setTranslateY(newTranslateY);
  }
  
  private void restoreCursor()
  {
    setCursor(saveMouseCursor);
  }
  
  private void saveAndSetCursor(Cursor cursor)
  {
    saveMouseCursor = getCursor();
    setCursor(cursor);
  }
}
